package com.bitejiuyeke.forum.controller;

import com.bitejiuyeke.forum.common.AppResult;
import com.bitejiuyeke.forum.common.ResultCode;
import com.bitejiuyeke.forum.config.AppConfig;
import com.bitejiuyeke.forum.model.Article;
import com.bitejiuyeke.forum.model.ArticleReply;
import com.bitejiuyeke.forum.model.User;
import com.bitejiuyeke.forum.services.IArticleReplyService;
import com.bitejiuyeke.forum.services.IArticleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 666
 * Date: 2024-02-16
 * Time: 13:30
 */
@Api( tags = "文章回复接口")
@Slf4j
@RestController
@RequestMapping("/reply")
public class ArticleReplyController {
   @Resource
   private IArticleReplyService iArticleReplyService;

   @Resource
   private IArticleService iArticleService;
   @ApiOperation("回复帖子")
   @PostMapping("/create")
   public AppResult create (HttpServletRequest request
   , @ApiParam("帖子id") @RequestParam("articleId") @NonNull Long  articleId
   , @ApiParam("帖子内容") @RequestParam("content") @NonNull String content){
   // 获取用户
       HttpSession session = request.getSession(false);
       User user = (User) session.getAttribute(AppConfig.USER_SESSION);
       //判断用户是否禁言
       if(user.getState() == 1){
           return AppResult.failed("用户已被禁言，不能进行回复操作");
       }
       //获取要回复帖子信息对象
       Article article = iArticleService.selectById(articleId);
       //是否存在或者已经删除
       if(article == null || article.getDeleteState() ==1 ){
           return  AppResult.failed(ResultCode.FAILED_NOT_EXISTS);
       }
       //构建回复对象
       ArticleReply articleReply = new ArticleReply();
       articleReply.setArticleId(articleId);   //要回复的帖子id
       articleReply.setContent(content);   // 回复的内容
       articleReply.setPostUserId(user.getId()); //回复的发送者
       //写入

       iArticleReplyService.create(articleReply);
      //返回结果
       return AppResult.success();
   }
@ApiOperation("根据帖子id获取回复列表")
@GetMapping("/getReplies")
   public AppResult<List<ArticleReply>> getRepliesByArticleId ( @ApiParam("帖子id") @RequestParam("articleId") @NonNull Long  articleId){
   //校验帖子是否存在
    Article article = iArticleService.selectById(articleId);
   if(article == null || article.getDeleteState() ==1 ){
       //不存在
       return  AppResult.failed(ResultCode.FAILED_NOT_EXISTS);
   }
    List<ArticleReply> articleReplies = iArticleReplyService.selectByArticleId(articleId);
   //返回结果
    return AppResult.success(articleReplies);
   }
}
